package com.itcast.controller;

import com.itcast.domain.User;

import com.itcast.service.UserService;
import com.itcast.utils.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;


@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/exportXls")
    @ResponseBody
    public void exportXls(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<User> users = userService.queryUserList2Excle();

        // 生成Excel文件
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        HSSFSheet sheet = hssfWorkbook.createSheet("用户数据");
        // 表头
        HSSFRow headRow = sheet.createRow(0);
        headRow.createCell(0).setCellValue("id");
        headRow.createCell(1).setCellValue("username");
        headRow.createCell(2).setCellValue("password");
        headRow.createCell(3).setCellValue("name");

        // 表格数据
        for (User user : users) {
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
            dataRow.createCell(0).setCellValue(user.getId());
            dataRow.createCell(1).setCellValue(user.getUsername());
            dataRow.createCell(2).setCellValue(user.getPassword());
            dataRow.createCell(3).setCellValue(user.getName());

        }

        // 下载导出
        // 设置头信息
        response.setContentType("application/vnd.ms-excel");
        String filename = "用户数据.xls";
        String agent = request.getHeader("user-agent");
        filename = FileUtils.encodeDownloadFilename(filename, agent);
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);

        OutputStream outputStream = response.getOutputStream();
        hssfWorkbook.write(outputStream);

        // 关闭
        hssfWorkbook.close();

    }

    public void excelUpload(@RequestParam MultipartFile file) {

        if (file == null) {
            throw new NullPointerException("文件不存在");
        }
        //获取文件名
        String name = file.getOriginalFilename();
        //进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）
        long size = file.getSize();
        if (name == null || ("").equals(name) && size == 0) {
            throw new NullPointerException("文件不存在");
        }

        HSSFWorkbook workbook = null;
        try {
            workbook = new HSSFWorkbook(new POIFSFileSystem(file.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取一共有多少sheet，然后遍历
        int numberOfSheets = workbook.getNumberOfSheets();
        for (int i = 0; i < numberOfSheets; i++) {
            HSSFSheet sheet = workbook.getSheetAt(i);

            //获取sheet中一共有多少行，遍历行（注意第一行是标题）
            int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
            User user;
            for (int j = 0; j < physicalNumberOfRows; j++) {
                if (j == 0) {
                    continue;//标题行
                }
             /*   int physicalNumberOfCells = physicalNumberOfRows[j].getPhysicalNumberOfCells();
                user = new User();
                for (int k = 0; k < physicalNumberOfCells; k++) {
                    HSSFCell cell = row.getCell(k);
                    //...
                }   */
            }
        }



            //批量导入。参数：文件名，文件。

        try {
            userService.uploadXls(name, file);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @RequestMapping("/findAll")
    public List<User> findAll( User user){
        return userService.findAll(user);
    }
}
